<template>
  <div class="app-container">
		<el-row>
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
		  <el-form-item label="客户端ID" prop="sbClientid">
		    <el-input
		      v-model="queryParams.sbClientid"
		      placeholder="请输入客户端ID"
		      clearable
		      @keyup.enter="handleQuery"
		    />
		  </el-form-item>
		  <el-form-item label="设备名称" prop="sbName">
		    <el-input
		      v-model="queryParams.sbName"
		      placeholder="请输入设备名称"
		      clearable
		      @keyup.enter="handleQuery"
		    />
		  </el-form-item>
		  <el-form-item>
		    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
		    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
		  </el-form-item>
		</el-form>
		</el-row>
	
	<el-row>
		<el-form :inline="true" label-width="68px">
		<el-form-item label="体测学生">
		  <el-select v-model="yuyue.schoolId" @change="schoolChange" placeholder="请选择学校" :disabled="isXxidFlag">
		    <el-option
		      v-for="d in dept_self"
		      :key="d.value"
		      :label="d.label"
		      :value="d.value"
		    />
		  </el-select>
		  <el-select v-model="yuyue.classId" @change="classChange" placeholder="请选择班级">
			<el-option
			  v-for="c in classList2"
			  :key="c.value"
			  :label="c.label"
			  :value="c.value"
			/>
		  </el-select>
		  <el-select v-model="yuyue.student" @change="studentChange" placeholder="请选学生" filterable>
			<el-option
			  v-for="c in studentList"
			  :key="c.id"
			  :label="c.xsName"
			  :value="c.id"
			/>
		  </el-select>
		</el-form-item>
		</el-form>
	</el-row>
	
	<div class="yy-sblist">
	<el-card style="width: 250px;" v-for="sb in shebeiList" >
	  <template #header>
			<div class="card-header">
				<el-tooltip class="box-item" effect="dark" :content="getDeptName(sb.sbXxid)" placement="top">
				<span style="float: left;">{{sb.sbName}}</span>
				</el-tooltip>
				<span style="float: right;">
					<el-tag type="warning" v-if="sb.sbIszx==0">离线</el-tag>
					<el-tag  v-if="sb.sbIszx==1">在线</el-tag>
					<el-button type="primary" size="small" @click="handleUpdateState(sb)" icon="RefreshLeft" style="margin-left: 5px;" />
				</span>
			</div>
	  </template>
	<div>
	<div class="yy-p-type" style="margin-bottom: 5px;">
	<el-tag type="warning">设备ID：{{sb.sbClientid}}</el-tag>
	<el-divider style="margin:10px 0"/>
	<el-tag type="danger">设备支持的体测项目</el-tag>
	</div>
	<el-scrollbar class="yy-p-tyleScrollbar">
		<div class="yy-sblist" style="justify-content: space-between;">
			<template v-for="(pro,index) in sb.shebeiProjectList" :key="index">
				<div v-if="pro.disable" style="cursor:pointer;" >
					<el-tag :type="pro.type">
						<svg-icon :icon-class="pro.icon" />
						<span :alt="pro.xmMc">
						{{pro.xmMc}}
						</span>
					</el-tag>
				</div>
			</template>
		</div>
	</el-scrollbar>
	</div>
	  <template #footer>
		  <el-button type="primary"  :icon="Timer" @click="yuyueshow(sb)">预约</el-button>
		 
	  </template>
	</el-card>
	</div>
	<pagination
	  v-show="total>0"
	  :total="total"
	  :pageSizes="[5,10,15]"
	  v-model:page="queryParams.pageNum"
	  v-model:limit="queryParams.pageSize"
	  @pagination="getList"
	/>
	
	
	  <el-drawer v-model="drawer" :direction="direction" :close-on-click-modal="false" :before-close="cancelClick" size="80%">
	    <template #header>
	      <h4>
			  <!-- <el-text class="mx-1" type="danger" size="large">姓名：{{yuyue.studentName}}</el-text> -->
			  <el-text class="mx-1" type="danger" style="margin-right: 50px;">姓名：{{yuyue.studentName}}</el-text>
			  <el-text class="mx-1" type="danger">设备：{{yuyue.sb.sbName}}({{yuyue.sb.sbClientid}})</el-text><br><br>
			  <el-text class="mx-1">预约时间、项目：</el-text>
			  <el-date-picker
						 v-model="yuyue.yydate"
						 value-format="YYYY-MM-DD"
						 type="date"
						 range-separator="-"
						 placeholder="日期"
						 @change="dateChange"
						 :clearable="false"
						 :disabled-date="disabledDate"
						 :shortcuts="shortcuts"
			  ></el-date-picker>
			  <el-select v-model="yuyue.projectid" placeholder="请选择预约项目">
				  <template :key="d.id"  v-for="d in yuyue.sb.shebeiProjectList">
					<el-option
					  :label="d.xmMc"
					  :value="d.id"
					  v-if="d.disable"
					/>
				  </template>
			  </el-select>
		  </h4>
	    </template>
	    <template #default>
	      <div class="yy-sblist">
			<el-card style="width: 200px;" v-for="yygz in yuyueguizeList2"  :v-loading="true" >
				  <template #header>
						<div class="card-header" style="font-size: 80%;">
							<el-tag type="info">{{yygz.gzName}}</el-tag>&nbsp;
							<el-tag type="danger" v-if="yygz.isyuyue==true">已预约</el-tag>
							<br>
							<el-tag type="warning">还可预约： {{yygz.renshu}}人</el-tag>
						</div>
				  </template>
				<div>
					<el-tag type="">
						<span :alt="yygz.gzName">
							{{yygz.startTime}} - {{yygz.endTime}} <br>
						</span>
					</el-tag>
					<el-scrollbar style="width: 170px;height: 100px;">
						<el-tag type="danger" class="yy-titlename" v-for="(item,index) in yygz.data">
								{{item.sname}} - <svg-icon :icon-class="getProIcon(item.proid)" />{{getProName(item.proid)}}<br>
						</el-tag>
						<span v-if="yygz.data.length<1 || yygz.data==null">
							<br/><br/>
							<el-tag type="info">
								<el-icon><CollectionTag /></el-icon>
								暂无预约
							</el-tag>
						</span>
					</el-scrollbar>
				</div>
				  <template #footer>
<!-- 					  <el-radio-group v-model="yuyue.yygz"> 
						<el-radio :label="yygz.id" size="large" @change="radioChange" border>选择</el-radio>
					  </el-radio-group> -->
						  <el-radio-group v-model="yygz.yuyuestatus"  size="small">
							<el-radio-button :label="true" :disabled="yygz.disable1"  @change="radioChange(yygz)">预约</el-radio-button>
							<el-radio-button :label="false" :disabled="yygz.disable2"  @change="radioChange(yygz)">取消</el-radio-button>
						  </el-radio-group>
				  </template>
			</el-card>
			
			
	      </div>
		  
	    </template>
	    <template #footer>
	      <div style="flex: auto;">
			  
			  <div  style="width: 100%;text-align: left;">
				<el-button  type="danger" plain @click="cancelClick">关闭</el-button>
			  </div>
	        <!-- <el-button type="primary" @click="confirmClick">确定</el-button> -->
	      </div>
	    </template>
	  </el-drawer>
	
  </div>
</template>

<script setup name="Yuyue">
import { Grid, MoreFilled,Timer} from '@element-plus/icons-vue'
import { checkPermi, checkRole } from "@/utils/permission"; // 1. 导入权限判断函数
import useUserStore from "@/store/modules/user";
import { listYuyue, getYuyue, addYuyue, updateYuyue,cancelYuyue } from "@/api/tc/yuyue";
import { listShebei,updateShebeiState} from "@/api/tc/shebei";
import { listDept } from "@/api/system/dept";
import { listStudent} from "@/api/tc/student";
import { listClass} from "@/api/tc/class";
import { listYuyueguize} from "@/api/tc/yuyueguize";
import { listProject} from "@/api/tc/project";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const yuyueList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const dept_self = ref([]);
const studentList = ref([]);
const classList = ref([]);
const classList2 = ref([]);
const isXxidFlag=ref(false);
const shebeiList = ref([]);
const tcProjectList = ref([]);
const yuyueguizeList = ref([]);
const yuyueguizeList2 = ref([]);
var defaultdate=new Date();
const tmpProPar={pageNum: 1,pageSize: 999,xmStatus:'1'};
const disabledDate = (time) => {
  return time.getTime() <(Date.now() - 3600 * 1000 * 24) 
}
const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '明天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '后天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + (3600 * 1000 * 24)*2)
      return date
    },
  }
]

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    xxid: null,
    sbClientid: null,
    yygz: null,
    status: null,
    yydata: null,
    yydate: null,
	sbXxid:null,
	sbName:null
  },
  yuyue:{
	  sb:{shebeiProjectList:[]},
	  schoolId:null,
	  classId:null,
	  studentId:null,
	  student:null,
	  yydate: null,
	  projectid:null,
	  yygz:null
	  
  },
  rules: {}
});

const { queryParams, form,yuyue } = toRefs(data);

const drawer = ref(false)
const direction = ref('rtl')



onMounted(() => {
	
	// getList();
	getProjectList();
	getDeptInfo();
})


const handleClose = (done) => {
	proxy.$modal.confirm('确认要关闭吗?').then(function () {
	  // proxy.$modal.msgSuccess("成功");
		console.log('1')
	  done();
	}).then(() => {
		console.log('then')
	}).catch(function () {
		console.log('catch')
	}).catch(function () {
		console.log('catch')
	});
}

function cancelClick() {
  drawer.value = false
}
// function confirmClick() {
// 	proxy.$modal.confirm('确认要保存吗?').then(function () {
// 	  // proxy.$modal.msgSuccess("成功");
// 	}).then(() => {
// 		console.log('then')
// 	}).catch(function () {
// 		console.log('catch')
// 	});
// }
function yuyueshow(sb){
	// console.log(sb)
	for(let i=0;i<sb.shebeiProjectList.length;i++){
		if(sb.shebeiProjectList[i].disable)break;
		if(i==sb.shebeiProjectList.length-1){
			proxy.$modal.msgError("此设备没有可支持体测项目！");
			return;
		}
	}
	if(yuyue.value.student==null){
          proxy.$modal.msgError("请选择学生！");
		  return;
	}
	
	proxy.$modal.loading('正在加载！')
	// return
	setTimeout(function() {
		yuyueguizeListClear();
		yuyue.value.sb=sb;
		// yuyue.value.yydate=null;
		yuyue.value.yydate=defaultdate.getFullYear()+"-"+( "00" +  (defaultdate.getMonth() + 1)).substr( -2 )+"-"+( "00" +  (defaultdate.getDate())).substr( -2 );
		// console.log(yuyue.value.yydate)
		yuyue.value.projectid=null;
		yuyue.value.yygz=null;
		drawer.value=true;
		dateChange(yuyue.value.yydate)
	}, 100);
}
function dateChange(e){
	// console.log(e)
	yuyue.value.yydate=e;
	if(e!=null && e!=''){
		yuyueguizeListClear();
		let par={"pageNum":1,"pageSize":999,"yydate":e,"xxid":queryParams.value.sbXxid,"sbClientid":yuyue.value.sb.sbClientid}
		// console.log(par)
		listYuyue(par).then(response => {
		  yuyueList.value = response.rows;
		  // console.log(yuyueList.value)
		  if(yuyueList.value.length>0){
			yuyueguizeList2.value.forEach((item,i2)=>{
				item.isyuyue=false; //是否预约标识
				item.disable1=false; //预约按钮
				item.disable2=false; //取消按钮
				item.data.length = 0;
			  yuyueList.value.forEach((item2,i)=>{
				  let count=0;
					if(item2.yygz==item.id){
						JSON.parse(item2.yydata).forEach((item3,i3)=>{
							item.data.push({"sname":item3.sname,"proid":item3.proid})
							let count=parseInt(item.renshu);
							item.renshu=count-1
							// console.log(item3.student)
							// console.log(yuyue.value.studentId)
							if(item3.student==yuyue.value.studentId){
								item.isyuyue=true; //已约标识
								item.disable1=true; //预约按钮
								// yuyue.value.yygz=item2.id;
							}
						  
						})
					}  
					  
				})  
				  
			  })
		  }
			proxy.$modal.closeLoading();
		  // total.value = response.total;
		  // loading.value = false;
		}).catch(()=>{
			loading.close();
		});
		
		
	}
}
function radioChange(e){
	let addremove=1; //1添加  2取消
	if(e.yuyuestatus){
		addremove=1;
	}else{
		if(!e.isyuyue){
			e.yuyuestatus=null;
			proxy.$modal.msgError("您没有预约!");
			return;
		}
		addremove=2;
	}
	yuyue.value.yygz=null;
	if((addremove==1 && isNull(yuyue.value.yydate,yuyue.value.projectid)) || (addremove==2 && isNull(yuyue.value.yydate)) ){
	  proxy.$modal.msgError("请选择日期 和 体测项目！");
	  e.yuyuestatus=null;
	}else{
		yuyue.value.yygz=e.id;
		// console.log(yuyue.value)
		if(isNull(yuyue.value.schoolId,yuyue.value.studentId,yuyue.value.yydate,yuyue.value.yygz,yuyue.value.sb.sbClientid)){
		   proxy.$modal.msgError("请选项所有数据!");
		   return;
		}
		let yydata={student:yuyue.value.studentId,sname:yuyue.value.studentName,proid:yuyue.value.projectid};
		let p={xxid:yuyue.value.schoolId,sbClientid:yuyue.value.sb.sbClientid,yygz:yuyue.value.yygz,yydate:yuyue.value.yydate,yydata:JSON.stringify(yydata)}
		// console.log(p)
		// return;
			
			proxy.$modal.confirm('确认要'+(addremove==1?"添加预约":"取消预约")+'吗?').then(function () {
			  // proxy.$modal.msgSuccess("成功");
				 
				if(addremove==1){
					// console.log("-------------添加预约")
				  addYuyue(p).then(response => {
					proxy.$modal.msgSuccess("新增预约成功");
					dateChange(p.yydate)
				  }).catch(()=>{
					// proxy.$modal.msgError("新增失败");
				  });
				}else{
					// console.log("-------------取消预约")
				  cancelYuyue(p).then(response => {
					proxy.$modal.msgSuccess("取消预约成功");
					dateChange(p.yydate)
				  }).catch(()=>{
					// proxy.$modal.msgError("取消失败");
				  });
				}
				
				// drawer.value = false
			}).then(() => {
				// console.log('then')
				e.yuyuestatus=null;
			}).catch(function () {
				// console.log('catch')
				e.yuyuestatus=null;
			});
	}
}




function getDeptInfo(){
		// console.log(userStore.user)
		if(checkRole(['admin','common'])){
			listDept({}).then(response => {
			  	response.data.forEach(function (element) {
			  	  // 遍历数组，对每个元素进行操作
				   if(element.xxlevel !=null && element.xxlevel != ''){
						dept_self.value.push({"value":element.deptId,"label":element.deptName});
				   }
			  	});
				yuyue.value.schoolId=dept_self.value[0].value;
				getClassList(null);
			});
			isXxidFlag.value=false;
		}else{
			dept_self.value.push({"value":userStore.user.deptId,"label":userStore.user.dept.deptName});
			yuyue.value.schoolId=dept_self.value[0].value;
			isXxidFlag.value=true;
			getClassList(yuyue.value.schoolId);
		}
}

function getClassList(bjid){
	listClass({"pageNum": 1,"pageSize": 500,"bjXxid" : bjid}).then(response => {
		response.rows.forEach(function (el) {
		  // 遍历数组，对每个元素进行操作
			classList.value.push({"value":el.id,"label":el.bjName,"xxid":el.bjXxid,"njid":el.bjNj});
		});
		if(classList.value.length > 0){
			yuyue.value.classId=classList.value[0].value;
			yuyue.value.classNjId=classList.value[0].njid;
			schoolChange(classList.value[0].xxid)
			getStudentList(dept_self.value[0].value,classList.value[0].value);
		}
		// getList();
	});
}
function getStudentList(a,b) {
			// console.log(a)
			// console.log(b)
   if(a==null || a==null || b=='' || b==''){
	   proxy.$modal.msgError("学校和班级不能为空!");
	   return;
   }
  // loading.value = true;
  listStudent({"pageNum": 1,"pageSize": 9999,"xsSchool" : a,"xsClassj" : b}).then(response => {
    studentList.value = response.rows;
	// console.log(response.rows)
    // loading.value = false;
  });
}
function schoolChange(e){
	classList2.value= classList.value.filter(function(currentValue,index,arr){
		// console.log(currentValue)
		return currentValue.xxid == e ;
	});
	
	if(classList2.value.length==0){
		yuyue.value.classId=null;
		yuyue.value.classNjId=null;
	}else{
		yuyue.value.classId=classList2.value[0].value;
		yuyue.value.classNjId=classList2.value[0].njid;
	}
	handleQuery();
}

function classChange(e){
	getStudentList(yuyue.value.schoolId,yuyue.value.classId);
}
function studentChange(e){
	for(let i=0;i<studentList.value.length;i++){
		if(studentList.value[i].id==e){
			yuyue.value.studentId=studentList.value[i].xsSfz;//学生身份证
			yuyue.value.sex=studentList.value[i].xsSex;
			yuyue.value.studentName=studentList.value[i].xsName;
			yuyue.value.photo=studentList.value[i].xsZp;
			return;
		}
	}
}

/** 查询体测项目列表 */
function getProjectList() {
  // loading.value = true;
  listProject(tmpProPar).then(response => {
    tcProjectList.value = response.rows;
    // loading.value = false;
  });
}
/** 查询设备列表 */
function getList() {
	// console.log("-----yuyue getList----")
  loading.value = true;
  
	if(checkRole(['admin','common'])){
	  // queryParams.value.sbXxid=null;
	  queryParams.value.sbXxid=yuyue.value.schoolId;
	}else{
	  queryParams.value.sbXxid=userStore.user.deptId;
	}
	// let par={"pageSize":999,"sbXxid":queryParams.value.xxid}
  listShebei(queryParams.value).then(response => {
	// console.log(response.rows)
    shebeiList.value = response.rows;
    total.value = response.total;
    loading.value = false;
	initsbListStatus();
	getyygzList();
  });
}
function initsbListStatus(){
	for(let i of shebeiList.value){
		let tmp=[];
		for(let p of tcProjectList.value){
			let tmp2={};
			tmp2["id"]=p.id;
			tmp2["icon"]=p.icon;
			tmp2["xmMc"]=p.xmMc;
			tmp2["disable"]=false;//项目不可用状态
			tmp2["type"]="info"
			tmp2["tooltip"]="";
			for(let j of i.shebeiProjectList){
				if(p["id"]==j["projectid"]){ //在设备下的项目 并且 在线的设备 && i.sbIszx==1
					tmp2["tooltip"]=p["xmMc"];
					tmp2["disable"]=true
					tmp2["type"]=""
				}
			}
			// tmp2["pro"]=p;
			tmp.push(tmp2);
		}
		i.shebeiProjectList=tmp;
		i.start=false;
		i.end=false;
		  // if(i.id == row.projectid) tcProjectTpRef.value.toggleRowSelection(i,true);
	}
	// console.log(shebeiList.value)
}










/** 查询预约规则列表 */
function getyygzList() {
	let par={"pageNum":1,"pageSize":999,"xxid":yuyue.value.schoolId}
  listYuyueguize(par).then(response => {
    yuyueguizeList.value = response.rows;
	yuyueguizeListClear();
  });
}



/** 查询体测预约列表 */
function getyyList() {
  listYuyue(queryParams.value).then(response => {
    yuyueList.value = response.rows;
  });
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}





/** 提交按钮 */
function submitForm() {
  proxy.$refs["yuyueRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateYuyue(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addYuyue(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}





/** 同步状态按钮操作 */
function handleUpdateState(sb) {
	updateShebeiState({id:sb.id,sbClientid:sb.sbClientid}).then(response => {
		// console.log(response)
		proxy.$modal.msgSuccess("设备状态刷新成功");
		sb.sbIszx=response.data.sbIszx;
	});
}
const getDeptName=(id)=>{
	for(let d of dept_self.value){
		 if(id==d.value){
			 return d.label;
		 }
	}
}
const getProName=(id)=>{
	for(let d of yuyue.value.sb.shebeiProjectList){
		 if(id==d.id){
			 return d.xmMc;
		 }
	}
}
const getProIcon=(id)=>{
	for(let d of tcProjectList.value){
		 if(id==d.id){
			 return d.icon;
		 }
	}
}
const isNull=(...par)=>{
	// par.forEach((v,i,par)=>{
	// 	console.log(v)
	// 	if(v==null  || v =='') return true;
	// })
	for(let i=0;i<par.length;i++){
		if(par[i]==null  || par[i] =='') {
			return true;
		}
	}
	return false;
}

const yuyueguizeListClear=()=>{
	yuyueguizeList2.value=[];
	yuyueguizeList.value.forEach((item,i)=>{
		yuyueguizeList2.value.push({"xxid":item.xxid,"startTime":item.startTime,"endTime":item.endTime,"id":item.id,"renshu":item.renshu,"gzName":item.gzName,
		"isyuyue":false,"yuyuestatus":null,data:[]});
	})
	//data:[{"sname":null,"proname":null}]
	// console.log("----------------")
	// console.log(yuyueguizeList2.value)
}



</script>
<style scoped>
	.yy-sblist{
		width:100%;
		display:flex;
		flex-wrap: wrap;
		align-items:flex-start;
		gap: 5px;
		
	}
	.yy-p-type {
	  display: flex;
	  justify-content: left;  
	  /* width:400px; */
	  flex-wrap: wrap;
	  /* height: 200px; */
	  font-size: 80%;
	  word-break: break-all;
	}
	.yy-p-tyleScrollbar{
	  height: 100px;
	  width: 100%;
	}
	.yy-titlename{
		font-size: 80%;
	}
	.el-drawer__header{
		 margin-bottom:5px !important;
	}
	
	.demo-date-picker {
	  display: flex;
	  width: 100%;
	  padding: 0;
	  flex-wrap: wrap;
	}
	
	.demo-date-picker .block {
	  padding: 30px 0;
	  text-align: center;
	  border-right: solid 1px var(--el-border-color);
	  flex: 1;
	}
	
	.demo-date-picker .block:last-child {
	  border-right: none;
	}
	
	.demo-date-picker .demonstration {
	  display: block;
	  color: var(--el-text-color-secondary);
	  font-size: 14px;
	  margin-bottom: 20px;
	}
</style>